<?php
namespace WDB;

/**
 * Framework configuration reader class.
 * 
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
final class Config
{   
    private static $data = NULL;
    
    /**@var string config file path */
    public static $source = NULL;
    
    /**
     * auto-load configuration file
     */
    private static function init()
    {
        if (self::$data === NULL)
        {
            self::$data = require self::$source;
        }
    }
    
    /**
     * Checks whether the specified configuration key exists
     * 
     * @param string $key key to verify
     * @return boolean
     */
    public static function exists($key)
    {
        self::init();
        try
        {
            Utils\Arrays::dotPath(self::$data, $key);
            return true;
        }
        catch (Exception\BadArgument $ex)
        {
            return false;
        }
    }
    
    /**
     * Returns configuration value for the specified key. Supports dot separated multi-dimensional array key
     * (@see Utils\Arrays::dotPath)
     * 
     * @param string configuration key to read
     * @return mixed
     * @throws Exception\ConfigKeyMissing
     */
    public static function read($key, $mandatory = FALSE)
    {
        self::init();
        try
        {
            return Utils\Arrays::dotPath(self::$data, $key);
        }
        catch (Exception\BadArgument $ex)
        {
            if ($mandatory) throw new Exception\ConfigKeyMissing("Mandatory configuration key $key not found.", 0, $ex);
            
        }
        return NULL;
    }
}
Config::$source = __DIR__.DIRECTORY_SEPARATOR.'../config.php';